<?php
# Login procedure

function login($username, $pass){
	if($data = _isUser($username, $pass)){
		$_SESSION['idusers']  = $data['idusers'];
		$_SESSION['username'] = $data['username'];
		if($data['home'] != null)
			header("Location: event.php?id=".$data['home']);
	}

	if($data = _isNewCommer($username, $pass)){
		$_SESSION['username'] = $data['username'];
		header('Location: account.php');
	}

	_removeExpiredUsers();
}

function _isUser($username, $pass){
	$c = connect();
	$r = mysql_query("SELECT idusers, username, events_idevents AS home FROM users WHERE username=\"$username\" AND password=\"$pass\"");
	if(! $r)
		return false;
	$row = mysql_fetch_assoc($r);
	mysql_close($c);
	return $row;
}

function _isNewCommer($username, $pass){
	$c      = connect();
	$r = mysql_query("SELECT username, password FROM newcommers WHERE username=\"$username\" AND password=\"$pass\"");
	if(! $r)
		return false;
	$row = mysql_fetch_assoc($r);
	mysql_close($c);
	return $row;
}

function _removeExpiredUsers(){
	$c     = connect();
	$date  = date_sub(date_create(), date_interval_create_from_date_string("T24H"));
	mysql_query("DELETE FROM newcommers WHERE signup_date < ".date_format($date, "Y-m-d H:i:s"));
	mysql_close($c);
}
?>
